package com.vogue.family.data.interceptor;

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.vogue.family.data.api.MeetingApiService;
import com.vogue.family.data.entity.AccessToken;
import com.vogue.family.data.entity.BaseResponse;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TokenInterceptor implements Interceptor {

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {

        Request request = chain.request();
        Response response = chain.proceed(request);

        Log.d(TokenInterceptor.class.getName(), "response.code=" + response.code());

        //判断token是否过期，与后台小伙伴协商，或者通过判断新旧token是否一致
        if (isTokenExpired(response)) {
            Log.d(TokenInterceptor.class.getName(), "自动刷新Token,然后重新请求数据");
            //同步请求方式，获取最新的Token
            String newToken = getNewToken();
            Log.e(TokenInterceptor.class.getName(), "intercept:新的请求头 "+newToken );
            //使用新的Token，创建新的请求
            Request newRequest = chain.request()
                    .newBuilder()
                    .header("Authorization", newToken)
                    .build();
            //重新请求
            return chain.proceed(newRequest);
        }

        return response;
    }

    //判断Token是否过期,我这里是因为Token过期会返回403,可以通过判断新旧token是否一致
    private boolean isTokenExpired(Response response) {
        if (response.code() == 401) {
            return true;
        }
        return false;
    }

    //用同步方法获取新的Token
    private String getNewToken(){

        String newToken = "";

        HashMap<String,String> data = new HashMap<>();
        data.put("grant_type","refresh_token");
        data.put("refresh_token","");

        RequestBody requestBody = RequestBody.create(new GsonBuilder().create().toJson(data),MediaType.parse("application/json; charset=utf-8"));

        OkHttpClient client = new OkHttpClient.Builder().readTimeout(10, TimeUnit.SECONDS).build();
        Request request = new Request.Builder()
                .addHeader("Authorization","Basic YmlsbDpiaWxs")
                .url(String.format("%s/api/oauth/token", MeetingApiService.BASE_URL))
                .post(requestBody)
                .build();
        Call call = client.newCall(request);

        try {
            Response response = call.execute();
            //坑人点，response.body().string()只能调用一次，否则会报java.lang.IllegalStateException: closed
            //第一次调用.body().string(),OkHttp就会默默地释放资源,再次调用就会抛出异常,有兴趣的可以去看源码

            String result = response.body().string();
            JSONObject jsonObject = new JSONObject(result);

            if (jsonObject.getInt("code")==401){

            }

            BaseResponse<AccessToken> tokenResponse = new GsonBuilder().create().fromJson(result, new TypeToken<BaseResponse<AccessToken>>(){}.getType());

            newToken = tokenResponse.getData().bearer();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return newToken;
    }

}
